/**
 * 获取redis连接,连接池方式
 *
 */
package com.ebocy.hammer.core.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisUtil {
	// redis连接池
	private static JedisPool jedisPool = null;
	private static String host = null;

	/**
	 * 初始化连接池
	 */
	static {
		if (jedisPool == null) {
			host = Config.redisAddres;
			if (host == null) {
				Config.getInstance().initRedis();
			}
			jedisPool = newJedisPool(Config.redisAddres, Config.redisPort);
		}
	}

	public static void main(String[] args) {
		Jedis js = getJedis();
		System.out.println(js.info());
	}

	/**
	 * 获取Jedis连接
	 * 
	 * @return
	 */
	public static Jedis getJedis() {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("获取redis连接失败!");
		}
		return jedis;
	}

	/**
	 * 关闭Jedis连接
	 * 
	 * @param jedis
	 */
	public static void closeJedis(Jedis jedis) {
		jedisPool.returnResource(jedis);
	}

	private static JedisPool newJedisPool(String host, int port) {
		JedisPoolConfig config = new JedisPoolConfig();
		// 最大活动连接
		int maxActive = Config.poolMaxActive;
		// 最大空闲连接
		int maxIdle = Config.poolMaxIdle;
		// 最大等待时间
		int maxWait = Config.poolMaxWait;
		boolean testOnBorrow = Boolean.parseBoolean(Config.poolTestOnBorrow);
		config.setMaxActive(maxActive);
		config.setMaxIdle(maxIdle);
		config.setMaxWait(maxWait);
		config.setTestOnBorrow(testOnBorrow);
		JedisPool pool = new JedisPool(config, host, port, Config.redisTimeOut);
		return pool;
	}

	/**
	 * jedis连接池重置
	 */
	public static void jedisPoolReset() {
		// 销毁连接池
		jedisPool.destroy();
		jedisPool = newJedisPool(Config.redisAddres, Config.redisPort);
	}
}